<template>
  <div id="order-apply-page" :style="{
    height:(this.getWinSize().height-this.getSafeArea().top-45)+'px'
  }" v-if="productList.length>0">
    <div style="width: 100%; position: fixed; top: 0px; background: #FFFFFF; z-index: 5" :style="{
      height:this.getSafeArea().top+'px'
    }"></div>
    <div class="page-title"
         :style="{top:(this.getSafeArea().top-4)+'px'}">
      <div id="back-button" @click="$router.back()">
        <i href="javascript:void(0)" class="el-icon-arrow-left"></i>
      </div>
      <span>商品退换货</span>
      <!--      <div class="button-box" :style="{-->
      <!--        top:(this.getSafeArea().top-3)+'px'-->
      <!--      }">-->
      <!--        -->
      <!--      </div>-->
    </div>

    <!--商品信息-->
    <div class="product-box"
         v-if="!$route.query.applyId || ($route.query.applyId>0 && orderApply.id>0)"
         style="position: relative;"
         :style="{top:(this.getSafeArea().top-4)+'px'}"
    >
      <div class="item" v-for="(product,index) in productList" :key="index"
           :class="{curr:productNumsMap[product.shopProductStockId]>0}">
        <div class="image">
          <img :src="product.productImage"/>
        </div>
        <div class="right">
          <div class="name">
            <span class="ovd_s" style="width: 90%" v-text="product.productName"></span>
          </div>
          <div class="model-nums">
            <span class="model" v-text="'型号:'+product.productModel"></span>
            <span class="nums" v-text="'购买数量: '+product.productNums"></span>
            <span class="nums red b" v-if="$route.query.applyId>0" v-text="orderApply.type.name+'数量: '+product.applyNums"></span>
          </div>
          <div class="price">
            <span style="color: #888888; font-size: 12px;">金额: </span>
            <span v-text="'￥'+ToMoney((product.productPrice*productNumsMap[product.shopProductStockId]).toFixed(2)-0)" v-if="$route.query.isInit==1"></span>
            <span v-text="'￥'+ToMoney((product.productPrice*product.applyNums).toFixed(2)-0)" v-if="$route.query.isInit!=1"></span>

            <el-input-number v-if="$route.query.isInit==1" size="mini" @change="calcMaxMoney"
                             v-model="productNumsMap[product.shopProductStockId]" class="product-nums-input"
                             :max="product.productNums" :min="0"></el-input-number>
            <span style="color: #888888; font-size: 12px; display: inline-block; margin-left: 20px;"
                  v-if="$route.query.isInit!=1">类型: </span>
            <el-tag type="warning" size="small" v-if="$route.query.isInit!=1" v-text="orderApply.type.name"></el-tag>
          </div>
        </div>
        <div class="c"></div>
      </div>
      <div class="c"></div>
    </div>


    <!--初始化提交表单-->
    <div class="init-form"
         style="position: relative;"
         :style="{top:(this.getSafeArea().top-4)+'px'}"
         v-if="!showInitInfo || orderApply.status.id>-1">
      <el-form ref="form" :model="initForm" label-width="80px" size="small">
        <el-form-item label="类型:">
          <el-select v-show="!showInitInfo" style="width: 60%;" v-model="initForm.type" placeholder="请选择 售后类型">
            <el-option :label="name" :value="index" v-for="(name,index) in typeArr"
                       :key="index"></el-option>
          </el-select>
          <span v-show="showInitInfo" v-text="typeArr[initForm.type]"></span>
        </el-form-item>
        <el-form-item label="金额:" v-if="initForm.type!==1">
          <el-input v-show="!showInitInfo" style="width: 60%;" type="number" v-model="initForm.money"></el-input>
          <span class="red b" v-show="showInitInfo" v-text="'￥'+ToMoney(initForm.money)"></span>
        </el-form-item>
        <el-form-item label="申请原因:">
          <el-select v-show="!showInitInfo" style="width: 60%;" v-model="initForm.reason" placeholder="请选择 退货理由">
            <el-option :label="reason" :value="reason" v-for="(reason,index) in reasonArr" :key="index"></el-option>
          </el-select>
          <span v-show="showInitInfo" v-text="initForm.reason"></span>
        </el-form-item>
      </el-form>
      <div align="center" v-if="!showInitInfo">
        <el-button type="danger" size="small" @click="submit">提交申请</el-button>
      </div>
    </div>

    <!--步骤信息-->
    <div class="item" v-if="currStep>0"
         style="position: relative; margin-bottom: 20px;"
         :style="{top:(this.getSafeArea().top-4)+'px'}"
    >
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in backStepList"
          :key="index"
          size="large"
          :timestamp="activity.createdAt"
          :class="getActiveClass(index)">
          <div class="step-content" @click="showInfo(index)" :class="isShowStep(index)">
            <div v-if="!activity.content">{{ (index + 1) + '.' + activity.tagName }}</div>
            <div v-if="activity.content">{{ (index + 1) + '.' + activity.tagName + '(' + activity.content + ')' }}</div>
            <el-button type="info" @click="showAddressInfo" style="position: absolute; right: -5px; top: 22px;"
                       v-if="orderApply.status.id!==6 && index===1 && currStep>1 && initForm.type!==2">查看商家收货地址
            </el-button>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>

    <!--物流信息-->
    <div class="express-form" style="position: relative; top: 40px; padding-bottom: 50px"
         v-if="(orderApply.type.id===0 || orderApply.type.id===1) && orderApply.status.id===1">
      <el-form ref="form" :model="initForm" label-width="80px" size="small">
        <!--        <el-form-item label="物流类型:">-->
        <!--          <el-select v-show="!showSendInfo" style="width: 60%;" v-model="expressForm.expressType"-->
        <!--                     placeholder="请选择 物流类型">-->
        <!--            <el-option :label="backItem.name" :value="backItem.key" v-for="(backItem,index) in expressTypeArr"-->
        <!--                       :key="index"></el-option>-->
        <!--          </el-select>-->
        <!--          <span v-show="showSendInfo" v-text="expressTypeArr[expressForm.expressType].name"></span>-->
        <!--        </el-form-item>-->
        <el-form-item label="物流单号:" v-if="expressForm.expressType<2">
          <el-input style="width: 90%;" v-model="expressForm.expressNumber"></el-input>
        </el-form-item>
        <el-form-item label="物流公司:" v-if="expressForm.expressType<2">
          <el-select style="width: 60%;" v-model="expressForm.expressCompany"
                     placeholder="请选择 物流公司">
            <el-option :label="reason" :value="reason" v-for="(reason,index) in expressCompanyArr"
                       :key="index"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <address-item style="background: #f1f1f1" :show-type="1" :is-re-choose="true" v-if="isGet"
                    :address-data="address"/>
      <div align="center">
        <el-button type="danger" size="small" @click="submitExpress">提交信息</el-button>
      </div>
    </div>

    <div style="height: 40px;width: 100%"></div>

    <div style="position: fixed; bottom: 0px; background: #fafafa; width: 100%; text-align: right; line-height: 45px;" v-if="orderApply.id>0">
      <!--1.已提交(未处理)-->
      <el-button @click="cancel" class="cancel-button" type="warning" icon="el-icon-refresh-left"
                 v-if="isCancel()">
        撤销
      </el-button>

      <!--2-1.【已经被商家】 && 【未申请-平台介入】-->
      <el-button @click="submitApplySystem" class="cancel-button" type="success" icon="el-icon-user-solid"
                 v-if="orderApply.status.id===6 && orderApply.systemStatus.id===0"
                 :disabled="orderApply.submitSystemHandlerNums>=2">
        申请平台介入
      </el-button>

      <!--2-2.【已经被商家】 && 【已申请-平台介入】-->
      <el-button @click="cancelApplySystem" class="cancel-button" type="success" icon="el-icon-user-solid"
                 v-if="orderApply.id>0 && orderApply.status.id===6 && orderApply.systemStatus.id===1">
        撤销平台介入
      </el-button>

      <!--2-2.【已经被商家】 && 【已申请-平台介入】 && 【平台介入处理中】-->
      <el-button type="primary" icon="el-icon-view" @click="showApplySystem"
                 v-if="orderApply.id>0 && orderApply.systemStatus.id>0">
        查看( {{ orderApply.systemStatus.name }} )
      </el-button>

      <!--3.换货(待收货)-->
      <el-button @click="receivedApply" class="cancel-button" type="warning" icon="el-icon-position"
                 v-if="orderApply.type.id===1 && orderApply.status.id===4">
        收货
      </el-button>
      &nbsp;&nbsp;
    </div>
  </div>
</template>

<script>
import AddressItem from '../common/AddressItem'

export default {
  name: 'OrderApply',
  components: {AddressItem},
  data: function () {
    return {
      limitSubmitCount: dict.LimitSystemApplyLogSubmit,
      submitCount: 0,
      productNumsMap: {},
      isGet: false,
      address: {},
      orderApply: {
        id: 0,
        type: {id: -1},
        status: {id: -1},
      },
      applyId: 0,
      // 当前退货所处步骤
      currStep: -1,
      currBeforeStepName: '',
      // 显示初始提交信息
      showInitInfo: true,
      // 显示寄件信息
      showSendInfo: false,
      // 物流公司
      expressCompanyArr: dict.ExpressCompanyList,
      typeArr: dict.OrderApplyTypeArr,
      // 退回-物流-类型
      // 退货类型
      reasonArr: [
        '不想要了',
        '实物的外观,不太喜欢',
        '买多了,买错了',
        '临时不想要了',
        '太贵了',
      ],
      // 最大退款金额
      maxMoney: 0,
      // 初次提交form
      initForm: {
        nums: demoData.product.nums,
        reason: '不想要了',
        money: 0,
        type: 0,
      },
      expressForm: {
        // 退回类型
        expressType: 0,
        expressCompany: '',
        expressNumber: '',
      },
      order: {},
      // 购买商品信息
      productList: [
        {
          'id': 4,
          'orderId': 4,
          'memberId': 18,
          'shopId': 7,
          'productId': 20,
          'productName': '百事可乐',
          'productImage': 'http://image.yangfankj.com/product/7/0/0.png',
          'productPrice': 5,
          'productModel': '常规',
          'productNums': 3,
          'applyStatus': null,
          'commission': 1,
          'applyType': null,
          'applyId': 0,
          'score': null
        }
      ],
      // 标准退货步骤列表
      backStepList: [
        {
          content: '',
          tagName: '提交申请',
          createdAt: '2018-04-12 20:46'
        }, {
          content: '',
          tagName: '商家处理',
          createdAt: '-',
        }, {
          content: '',
          tagName: '用户寄件',
          createdAt: '-',
        }, {
          content: '',
          tagName: '商家收件',
          createdAt: '-'
        }]
    }
  },
  mounted () {
    /*     if (this.$route.query.productData) {
          var product = JSON.parse(decodeURI(this.$route.query.productData))
          if (product.applyId > 0) {
            this.product = product
            this.applyId = product.applyId
            this.currStep = 1
            this.getDetail()
          } else {
            this.product = product
            this.initForm.nums = this.product.nums
            this.initForm.money = this.product.allPrice
            this.initForm.orderProductId = this.product.orderProductId
          }
        } */
    if (this.$route.query.isInit == 1) {
      this.showInitInfo=false
      this.getProductList()
    } else {
      let $this=this
      $this.getDetail()
      $this.bus.$on('OrderApplyInfoUpdate',function (id) {
        $this.orderApply.id=0
        $this.getDetail(id)
      })
    }
  },
  methods: {
    showApplySystem: function () {
      this.bus.$emit('ShowSystemApplyLogDialogCallBus', this.orderApply.id, 'OrderApply')
    },
    cancelApplySystem: function () {
      this.$confirm('您确认要进行该操作?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let $this = this
        $this.MyRequest($this.ApiDoNameMember + 'OrderApply/cancelApplySystem', {id: $this.orderApply.id}, function () {
          location.reload()
          $this.$forceUpdate()
        }, function (msg) {
          $this.$message.error(msg)
        })
      })
    },
    // 申请平台介入
    submitApplySystem: function () {
      let $this = this
      if ($this.limitSubmitCount <= $this.submitCount) {
        return $this.$message.error('申请平台介入次数不能超过: ' + $this.limitSubmitCount + '次')
      }
      $this.$prompt('请输入 【申请平台介入】原因', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\w\W]{1,100}$/,
        inputErrorMessage: '申请原因,长度在(1,100)位之间'
      }).then(({value}) => {
        if (value.length > 100) {
          return $this.successTip('申请原因,必须在100个字符以内')
        }
        $this.isLoading = true
        $this.MyRequest($this.ApiDoNameMember + 'OrderApply/submitApplySystem', {
          id: $this.orderApply.id,
          reason: value
        }, function (data) {
          $this.isLoading = false
          location.reload()
          $this.$forceUpdate()
        }, function (data) {
          $this.isLoading = false
          $this.$forceUpdate()
          $this.successTip(data.message, 'error')
        })
      })
    },
    // 重新提交
    reSubmit: function () {
      this.$confirm('您确认要【重新提交】吗，这样会删除您之前的申请?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let $this = this
        $this.MyRequest($this.ApiDoNameMember + 'OrderApply/reSubmit', {id: $this.orderApply.id}, function () {
          $this.$router.back()
          $this.$forceUpdate()
        }, function (msg) {
          $this.$message.error(msg)
        })
      })
    },
    showAddressInfo: function () {
      var addressInfo = this.orderApply.addressInfo
      var addressDetail = addressInfo.province + ',' + addressInfo.city + ',' + addressInfo.county + '  ' + addressInfo.address
      this.$alert('<div><div>收货人: ' + addressInfo.name + ',' + addressInfo.mobile + '</div><div>' + addressDetail + '</div></div>', '商家退货地址', {
        dangerouslyUseHTMLString: true,
        // confirmButtonText: '确定',
        callback: action => {

        }
      })
    },
    // 是否可撤销
    isCancel: function () {
      if (this.orderApply.type.id === 0) {
        return this.orderApply.status.id === 0
      }
      if (this.orderApply.type.id === 1) {
        return this.orderApply.status.id === 0
      }
    },
    // 合并当前操作记录 + 标准记录
    mergeStep: function (logList) {
      var stepArr = dict.OrderApplyStepNameArr[this.initForm.type]
      // console.log('stepArr',stepArr)
      var backStepList = []
      logList.forEach(function (log, _index) {
        var stepItem = {
          content: log.content,
          tagName: log.tagName,
          createdAt: log.createdAt,
          isComplete: log.isComplete,
        }
        /* stepArr.forEach(function (stepName, index) {
          if (log.tagName === stepName) {
            stepItem.createdAt = log.createdAt
            stepItem.content = log.content
          }
        }) */
        backStepList.push(stepItem)
      })

      this.currStep = backStepList.length
      this.currBeforeStepName = backStepList[backStepList.length - 1].tagName

      // 补充后续-空步骤
      var currStepIsComplete = backStepList[backStepList.length - 1].isComplete
      if (currStepIsComplete !== 1) {
        stepArr.forEach(function (stepName, index) {
          var isAdd = false
          backStepList.forEach(function (value, _index) {
            if (stepName === value.tagName) {
              isAdd = true
            }
          })
          if (!isAdd) {
            backStepList.push({
              content: '',
              tagName: stepName,
              createdAt: '-'
            })
          }
        })
      }

      this.backStepList = backStepList
      this.$forceUpdate()
    },

    // 获取-退换货详情
    getDetail: function (id) {
      let $this = this
      $this.MyRequest($this.ApiDoNameMember + 'OrderApply/getDetail', {orderApplyId: id?id:this.$route.query.applyId}, function (data) {
        $this.initForm.nums = data.orderApply.nums
        $this.initForm.money = data.orderApply.money
        $this.initForm.type = data.orderApply.type.id
        $this.initForm.reason = data.orderApply.reason
        $this.orderApply = data.orderApply
        $this.getSystemSubmitCount()
        var productList = []
        data.orderApply.productData.forEach(function (item, index) {
          productList.push({
            productId: item.id,
            productName: item.name,
            productImage: item.image,
            productPrice: item.price,
            productModel: item.model,
            productNums: item.nums,
            applyNums: item.applyNums,
          })
        })
        $this.productList = productList
        $this.mergeStep(data.orderApplyLog)

        if (data.orderApply.status.id === 1) {
          $this.getDefaultAddress()
        }
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    // 获取-默认地址
    getDefaultAddress: function () {
      var $this = this
      var addressId = 0
      if ($this.$route.query.chooseAddressId) {
        addressId = $this.$route.query.chooseAddressId
      }
      $this.MyRequest($this.ApiDoNameMember + 'MemberAddress/getDetail', {id: addressId}, function (data) {
        if (data.id) {
          $this.address.id = data.id
          $this.address.name = data.name
          $this.address.province = data.province
          $this.address.city = data.city
          $this.address.county = data.county
          $this.address.mobile = data.mobile
          $this.address.address = data.address
          $this.address.isDefault = data.isDefault === 1
        }
        $this.isGet = true
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    // 是否显示当前步骤信息
    isShowStep: function (index) {
      if (index === 0) {
        return this.showInitInfo ? 'curr-show' : 'curr-close'
      }
      // if (index === 2) {
      //   return this.showSendInfo ? 'curr-show' : 'curr-close'
      // }
    },
    // 提交物流信息
    submitExpress: function () {
      let $this = this
      var form = Object.assign({}, $this.expressForm)
      var regExp = /^[a-zA-Z0-9]{5,50}$/;
      if (!regExp.test(form.expressNumber+'')){
        return $this.$message.error('快递单号 必须是由(A-Za-z0-9)组成，长度在5~50位之间')
      }
      if (!$this.address || !$this.address.id) {
        return $this.successTip('地址信息 不能为空', 'warning')
      }
      if (!form.expressCompany) {
        return $this.successTip('快递公司 不能为空', 'warning')
      }
      form.addressId = $this.address.id
      form.orderApplyId = $this.orderApply.id
      $this.MyRequest($this.ApiDoNameMember + 'OrderApply/submitExpressApply', form, function (data) {
        $this.successTip('提交成功!')
        $this.$router.push('OrderList')
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    // 显示操作过的信息: 0.初始提交,2.发件信息
    showInfo (index) {
      if (index === 0) {
        if (this.currStep === 0) {
          return
        }
        // this.showSendInfo = false
        // this.showInitInfo = !this.showInitInfo
      }
      // if (index === 2) {
      //   if (this.currStep === 2) {
      //     return
      //   }
      //   this.showInitInfo = false
      //   this.showSendInfo = !this.showSendInfo
      // }
    },
    // 获取-订单-商品列表(用于首次提交退换货)
    getProductList: function () {
      let $this = this
      $this.MyRequest($this.ApiDoNameMember + 'Order/getDetail', {id: $this.$route.query.orderId}, function (data) {
        $this.productList = data.orderProductList
        var productNumsForm = {}
        data.orderProductList.forEach(function (product, index) {
          productNumsForm[product.shopProductStockId] = product.productNums - 0
        })
        $this.order = data.order
        $this.maxMoney = data.order.price
        $this.initForm.money = data.order.price
        $this.productNumsMap = productNumsForm
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    calcMaxMoney: function () {
      let $this = this
      var currMaxProductMoney = 0
      $this.productList.forEach(function (product, index) {
        var nums = $this.productNumsMap[product.shopProductStockId]
        var tmpPrice=(nums * product.productPrice).toFixed(2)-0;
        currMaxProductMoney = (currMaxProductMoney+tmpPrice).toFixed(2)-0
      })
      $this.maxMoney = currMaxProductMoney
      $this.initForm.money = currMaxProductMoney
      $this.$forceUpdate()
    },
    // 初始提交
    submit: function () {
      let $this = this
      var money = $this.initForm.money
      var shopStockIds = Object.keys($this.productNumsMap)
      var orderProductNumsMapList = []
      shopStockIds.forEach(function (shopStockId, index) {
        if ($this.productNumsMap[shopStockId] > 0) {
          orderProductNumsMapList.push({
            shopProductStockId: shopStockId,
            nums: $this.productNumsMap[shopStockId],
          })
        }
      })
      if (orderProductNumsMapList.length === 0) {
        return $this.successTip('退货数量必须大于: 0', 'warning')
      }
      if ($this.initForm.type !== 1) {
        if (money < 0.01) {
          return $this.successTip('最小退款金额为: 0.01', 'warning')
        }
      } else {
        money = 0
      }
      if (money > $this.maxMoney) {
        return $this.successTip('退款金额不能超过: ' + $this.maxMoney, 'warning')
      }
      var form = {
        orderId: $this.$route.query.orderId,
        orderProductNumsMapList: JSON.stringify(orderProductNumsMapList),
        money: money,
        type: $this.initForm.type,
        reason: $this.initForm.reason,
      }
      $this.MyRequest($this.ApiDoNameMember + 'OrderApply/submit', form, function (data) {
        $this.successTip('提交成功!')
        $this.$router.back()
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    // 获取状态标记类
    getActiveClass: function (index) {
      var isRefuse = this.orderApply.status.id === 6 && this.orderApply.systemStatus.id === 3
      var checkIndex = index
      if (isRefuse) {
        checkIndex += 1
      }
      if (checkIndex < this.currStep) {
        return 'over'
      } else if (checkIndex === this.currStep) {
        return 'curr'
      } else {
        return ''
      }
    },
    // 换货确认收货
    receivedApply: function () {
      let $this = this
      $this.$confirm('您是否确认进行该操作?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        $this.MyRequest($this.ApiDoNameMember + 'OrderApply/receivedApply', {orderApplyId: $this.orderApply.id}, function (data) {
          $this.successTip('收货成功!')
          $this.$router.back()
          $this.$forceUpdate()
        }, function (msg) {
          $this.$message.error(msg)
        })
      })
    },
    // 撤销申请
    cancel: function () {
      let $this = this
      $this.$confirm('您是否确认进行该操作?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        $this.MyRequest($this.ApiDoNameMember + 'OrderApply/cancelApply', {orderApplyId: $this.orderApply.id}, function (data) {
          $this.successTip('撤销成功!')
          $this.$router.back()
          $this.$forceUpdate()
        }, function (msg) {
          $this.$message.error(msg)
        })
      })
    },
    // 撤销申请
    getSystemSubmitCount: function () {
      let $this = this
      $this.MyRequest($this.ApiDoNameMember + 'OrderApply/getSystemApplyLogSumbitCount', {
        type: 'OrderApply',
        params: $this.orderApply.id
      }, function (submitCount) {
        $this.submitCount = submitCount
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    }
  }
}
</script>

<style scoped>

</style>
